<script setup lang="ts">
import {
  ElDescriptions,
  ElDescriptionsItem,
  ElImage,
  ElTag,
  ElLink,
  ElTabs,
  ElTabPane,
  ElInput,
  ElText,
  ElButton,
  ElUpload,
  ElIcon,
  ElDialog,
  ElSelect,
  ElOption,
  ElDatePicker
} from 'element-plus'
import {
  getTableDetApi,
  initAppName,
  getOcrApi,
  saveTableApi,
  putTableApi,
  putDriverApi
} from '@/api/data'
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { useGuide } from '@/hooks/web/useGuide'
import { ref, onMounted } from 'vue'
import { Plus } from '@element-plus/icons-vue'
import { useUserStore } from '@/store/modules/user'
// import { genFileId } from 'element-plus'
import type { UploadInstance, UploadRawFile } from 'element-plus'
import { Motorcade } from './types'
import { refreshApi } from '@/api/login'
const uploadRef1 = ref<UploadInstance>()
const uploadRef2 = ref<UploadInstance>()
const uploadRef3 = ref<UploadInstance>()

initAppName('Motorcades')
const apiObj = ref<any>()
const { t } = useI18n()

const { drive } = useGuide()
const baseUrl = 'http://test.elaihui.net:888'

const downloadFile = () => {
  const link = document.createElement('a')
  link.href = 'https://example.com/file.pdf'
  link.download = 'example.pdf'
  link.click()
}

const guideStart = () => {
  drive()
}
const activeName = ref('first')
const on_off = ref(true)
const motoData = ref<Motorcade>({})

const userStore = useUserStore()
onMounted(async () => {
  const data = await (await getTableDetApi(userStore.getUserInfo?.cid)).data.data
  if (data) {
    motoData.value = data
    apiObj.value = putTableApi
    if (motoData.value)
      fileList1.value.push({ name: 'businessLicense', url: motoData.value.businessLicense })
    if (motoData.value && motoData.value.agreement != '') {
      motoData.value.agreement.split(',').forEach((item: string) => {
        fileList2.value.push({ name: 'agreement', url: item })
      })
    }
    if (motoData.value && motoData.value.certificate != '') {
      motoData.value.certificate.split(',').forEach((item: string) => {
        fileList3.value.push({ name: 'certificate', url: item })
      })
    }
  } else {
    apiObj.value = saveTableApi
  }

  console.log(motoData.value)
})

import type { UploadProps, UploadUserFile } from 'element-plus'
import { before } from 'node:test'
const submitUpload = async () => {
  await uploadRef1.value!.submit()
  await uploadRef2.value!.submit()
  await uploadRef3.value!.submit()
}

const beforeUpload = (rawFile: UploadRawFile) => {
  console.log(rawFile)
}

const fileList1 = ref<UploadUserFile[]>([
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  // }
])
const fileList2 = ref<UploadUserFile[]>([
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  // }
])
const fileList3 = ref<UploadUserFile[]>([
  // {
  //   name: 'food.jpeg',
  //   url: 'https://fuss10.elemecdn.com/3/63/4e7f3a15429bfda99bce42a18cdd1jpeg.jpeg?imageMogr2/thumbnail/360x360/format/webp/quality/100'
  // }
])
const dialogImageUrl = ref('')
const agreement = ref([])
const certificate = ref([])
const dialogVisible = ref(false)

const handleSuccess1: UploadProps['onSuccess'] = async (response, uploadFile, uploadFiles) => {
  console.log(response)
  console.log(uploadFiles)
  motoData.value.businessLicense = response.data[0]
  const ocrRes = await getOcrApi({ url: motoData.value.businessLicense, type: 'Business' })
  const jsonData = JSON.parse(ocrRes.data.body.data).data
  console.log(jsonData)
  motoData.value.name = jsonData.companyName
  motoData.value.formed = jsonData.RegistrationDate
  motoData.value.address = jsonData.businessAddress
  motoData.value.type = jsonData.companyType
  motoData.value.lealPerson = jsonData.legalPerson
  motoData.value.regMoney = jsonData.registeredCapital
}
const handleSuccess2: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
  console.log(response)
  console.log(uploadFiles)
  motoData.value.agreement = response.data[0]
  agreement.value.push(response.data[0])
  console.log(agreement.value)
}
const handleSuccess3: UploadProps['onSuccess'] = (response, uploadFile, uploadFiles) => {
  console.log(response)
  console.log(uploadFiles)
  motoData.value.certificate = response.data[0]
  certificate.value.push(response.data[0])
}

const handleRemove: UploadProps['onRemove'] = (uploadFile, uploadFiles) => {
  console.log(uploadFile, uploadFiles)
}
const handleExceed: UploadProps['onExceed'] = (files) => {
  uploadRef1.value!.clearFiles()
  const file = files[0] as UploadRawFile
  file.uid = new Date().getTime()
  console.log(file)
  uploadRef1.value!.handleStart(file)
}
const handlePictureCardPreview: UploadProps['onPreview'] = (uploadFile) => {
  console.log(uploadFile)
  dialogImageUrl.value = uploadFile.url!
  dialogVisible.value = true
}
const handleSave = async () => {
  motoData.value.agreement = agreement.value.join(',')
  motoData.value.certificate = certificate.value.join(',')
  console.log(motoData.value)
  // motoData.value.id = undefined
  const res = await apiObj.value(motoData.value)
  if (apiObj.value === saveTableApi) {
    const userInfo = userStore.getUserInfo
    // userInfo.cid = res.data.data.id
    // userStore.setUserInfo(userInfo)
    await putDriverApi({ id: +userInfo.userId, motorcadeId: res.data.data.id })
    userStore.setUserInfo(null)
    const refresh_user = await refreshApi({ refresh_token: userInfo.refresh_token })
    userStore.setUserInfo(refresh_user.data)
  }
  console.log(userStore.getUserInfo)
}
</script>

<template>
  <ContentWrap title="供应商信息" :message="t('guideDemo.message')">
    <el-tabs v-model="activeName" class="demo-tabs" @tab-click="handleClick">
      <el-tab-pane label="基本信息" name="first">
        <el-descriptions
          title="上传文件名暂不支持中文"
          direction="vertical"
          border
          style="margin-top: 20px"
        >
          <template #extra>
            <el-button type="primary" @click="on_off = !on_off">填写</el-button>
          </template>
          <el-descriptions-item :rowspan="2" :width="140" label="企业营业执照" align="center">
            <el-upload
              v-model:file-list="fileList1"
              :action="baseUrl + '/api/tool/oss/originals'"
              name="files"
              :data="{ types: 1 }"
              list-type="picture-card"
              ref="uploadRef1"
              :limit="1"
              :on-exceed="handleExceed"
              :auto-upload="true"
              :on-success="handleSuccess1"
              :before-upload="beforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <el-icon class="avatar-uploader-icon"><Plus /></el-icon>
            </el-upload>
          </el-descriptions-item>
          <el-descriptions-item label="公司名称">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.name : ''
            }}</el-text>
            <el-input v-else v-model="motoData.name" style="width: 200px" placeholder="请输入"
          /></el-descriptions-item>
          <el-descriptions-item label="公司性质">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.type : ''
            }}</el-text>
            <el-select v-else v-model="motoData.type" placeholder="Select" style="width: 240px">
              <el-option
                v-for="item in []"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-descriptions-item>

          <el-descriptions-item label="城市">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.city : ''
            }}</el-text>
            <el-input v-else v-model="motoData.city" style="width: 200px" placeholder="请输入"
          /></el-descriptions-item>
          <el-descriptions-item label="法人代表">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.lealPerson : ''
            }}</el-text>
            <el-input
              v-else
              v-model="motoData.lealPerson"
              style="width: 200px"
              placeholder="请输入"
            />
          </el-descriptions-item>
          <el-descriptions-item label="注册资金">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.regMoney : ''
            }}</el-text>
            <el-input v-else v-model="motoData.regMoney" style="width: 200px" placeholder="请输入"
          /></el-descriptions-item>
          <el-descriptions-item label="成立时间">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.formed : ''
            }}</el-text>
            <el-date-picker v-else v-model="motoData.formed" type="date" placeholder="Pick a day" />
          </el-descriptions-item>
          <el-descriptions-item label="业务联系人姓名">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.contactPerson : ''
            }}</el-text>
            <el-input
              v-else
              v-model="motoData.contactPerson"
              style="width: 200px"
              placeholder="请输入"
          /></el-descriptions-item>
          <el-descriptions-item span="2" label="办公地址">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.offcie : ''
            }}</el-text>
            <el-input v-else v-model="motoData.offcie" style="width: 200px" placeholder="请输入"
          /></el-descriptions-item>
          <el-descriptions-item label="联系电话">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.phone : ''
            }}</el-text>
            <el-input v-else v-model="motoData.phone" style="width: 200px" placeholder="请输入"
          /></el-descriptions-item>

          <el-descriptions-item span="2" label="注册地址">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.address : ''
            }}</el-text>
            <el-input v-else v-model="motoData.address" style="width: 200px" placeholder="请输入"
          /></el-descriptions-item>
          <el-descriptions-item label="与易来回协议到期时间">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.expireDate : ''
            }}</el-text>
            <el-date-picker
              v-else
              v-model="motoData.expireDate"
              type="date"
              placeholder="Pick a day"
          /></el-descriptions-item>

          <el-descriptions-item span="2" label="收款银行名称">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.bankName : ''
            }}</el-text>
            <el-input v-else v-model="motoData.bankName" style="width: 200px" placeholder="请输入"
          /></el-descriptions-item>

          <el-descriptions-item span="2" label="银行账号">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.bankAccount : ''
            }}</el-text>
            <el-input
              v-else
              v-model="motoData.bankAccount"
              style="width: 200px"
              placeholder="请输入"
          /></el-descriptions-item>

          <el-descriptions-item span="2" label="开户行地址">
            <el-text v-if="on_off" style="width: 200px">{{
              motoData ? motoData.bankAddress : ''
            }}</el-text>
            <el-input
              v-else
              v-model="motoData.bankAddress"
              style="width: 200px"
              placeholder="请输入"
          /></el-descriptions-item>
        </el-descriptions>
      </el-tab-pane>
      <el-tab-pane label="文件信息" name="second">
        <el-descriptions class="margin-top" title="上传文件要求" :column="1" :size="size" border>
          <template #extra>
            <el-link
              style="padding-right: 8px"
              href="http://test.elaihui.net:888/files/f2.docx"
              type="success"
              target="_blank"
              >规范流程</el-link
            >
            <el-link
              style="padding-right: 8px"
              href="http://test.elaihui.net:888/files/f0.docx"
              type="success"
              target="_blank"
              >服务协议</el-link
            >
            <el-link
              style="padding-right: 8px"
              href="http://test.elaihui.net:888/files/f1.xlsx"
              type="success"
              target="_blank"
              >价格细则</el-link
            >
            <!-- <el-button type="primary" @click="submitUpload">上传</el-button> -->
            <el-link href="http://test.elaihui.net:888/files/f3.docx" type="success" target="_blank"
              >工作说明</el-link
            >
          </template>
          <!-- <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <user />
                </el-icon>
                企业营业执照副本
              </div>
            </template>

            <el-upload
              v-model:file-list="fileList1"
              action="baseUrl/api/tool/oss/originals"
              name="files"
              :data="{ types: 1 }"
              list-type="picture-card"
              ref="uploadRef1"
              :auto-upload="false"
              :on-success="handleSuccess1"
              :before-upload="beforeUpload"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-descriptions-item> -->
          <!-- <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <iphone />
                </el-icon>
                收款银行名称、地址和账号
              </div>
            </template>
            18100000000
          </el-descriptions-item> -->
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <location />
                </el-icon>
                敲章的合作协议
              </div>
            </template>
            <el-upload
              v-model:file-list="fileList2"
              :action="baseUrl + '/api/tool/oss/originals'"
              name="files"
              :data="{ types: 2 }"
              list-type="picture-card"
              ref="uploadRef2"
              node-key="upload2"
              :on-success="handleSuccess2"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-descriptions-item>
          <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <tickets />
                </el-icon>
                经营许可证
              </div>
            </template>
            <el-upload
              v-model:file-list="fileList3"
              :action="baseUrl + '/api/tool/oss/originals'"
              name="files"
              :data="{ types: 3 }"
              list-type="picture-card"
              ref="uploadRef3"
              :on-success="handleSuccess3"
              :on-preview="handlePictureCardPreview"
              :on-remove="handleRemove"
            >
              <el-icon><Plus /></el-icon>
            </el-upload>
          </el-descriptions-item>
          <!-- <el-descriptions-item>
            <template #label>
              <div class="cell-item">
                <el-icon :style="iconStyle">
                  <office-building />
                </el-icon>
                Address
              </div>
            </template>
            No.1188, Wuzhong Avenue, Wuzhong District, Suzhou, Jiangsu Province
          </el-descriptions-item> -->
        </el-descriptions>
      </el-tab-pane>
    </el-tabs>
    <div class="mb-10px" style="margin-top: 30px">
      <el-button type="primary" @click="handleSave">提交</el-button>
    </div>
    <el-dialog v-model="dialogVisible">
      <img w-full style="max-width: 100%" :src="dialogImageUrl" alt="Preview Image" />
    </el-dialog>
  </ContentWrap>
</template>

<style scoped>
.avatar-uploader .avatar {
  width: 128px;
  height: 128px;
  display: block;
}
</style>

<style>
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 128px;
  height: 128px;
  text-align: center;
}
</style>
